/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pojo.Buy;
import pojo.User;
import pojo.Product;

/**
 *
 * @author khalifaabdelaziz
 */
public class BuyJpaController implements Serializable {

    public BuyJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Buy buy) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User userId = buy.getUserId();
            if (userId != null) {
                userId = em.getReference(userId.getClass(), userId.getId());
                buy.setUserId(userId);
            }
            Product productId = buy.getProductId();
            if (productId != null) {
                productId = em.getReference(productId.getClass(), productId.getId());
                buy.setProductId(productId);
            }
            em.persist(buy);
            if (userId != null) {
                userId.getBuyList().add(buy);
                userId = em.merge(userId);
            }
            if (productId != null) {
                productId.getBuyList().add(buy);
                productId = em.merge(productId);
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Buy buy) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Buy persistentBuy = em.find(Buy.class, buy.getId());
            User userIdOld = persistentBuy.getUserId();
            User userIdNew = buy.getUserId();
            Product productIdOld = persistentBuy.getProductId();
            Product productIdNew = buy.getProductId();
            if (userIdNew != null) {
                userIdNew = em.getReference(userIdNew.getClass(), userIdNew.getId());
                buy.setUserId(userIdNew);
            }
            if (productIdNew != null) {
                productIdNew = em.getReference(productIdNew.getClass(), productIdNew.getId());
                buy.setProductId(productIdNew);
            }
            buy = em.merge(buy);
            if (userIdOld != null && !userIdOld.equals(userIdNew)) {
                userIdOld.getBuyList().remove(buy);
                userIdOld = em.merge(userIdOld);
            }
            if (userIdNew != null && !userIdNew.equals(userIdOld)) {
                userIdNew.getBuyList().add(buy);
                userIdNew = em.merge(userIdNew);
            }
            if (productIdOld != null && !productIdOld.equals(productIdNew)) {
                productIdOld.getBuyList().remove(buy);
                productIdOld = em.merge(productIdOld);
            }
            if (productIdNew != null && !productIdNew.equals(productIdOld)) {
                productIdNew.getBuyList().add(buy);
                productIdNew = em.merge(productIdNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = buy.getId();
                if (findBuy(id) == null) {
                    throw new NonexistentEntityException("The buy with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Buy buy;
            try {
                buy = em.getReference(Buy.class, id);
                buy.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The buy with id " + id + " no longer exists.", enfe);
            }
            User userId = buy.getUserId();
            if (userId != null) {
                userId.getBuyList().remove(buy);
                userId = em.merge(userId);
            }
            Product productId = buy.getProductId();
            if (productId != null) {
                productId.getBuyList().remove(buy);
                productId = em.merge(productId);
            }
            em.remove(buy);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Buy> findBuyEntities() {
        return findBuyEntities(true, -1, -1);
    }

    public List<Buy> findBuyEntities(int maxResults, int firstResult) {
        return findBuyEntities(false, maxResults, firstResult);
    }

    private List<Buy> findBuyEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Buy.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Buy findBuy(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Buy.class, id);
        } finally {
            em.close();
        }
    }

    public int getBuyCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Buy> rt = cq.from(Buy.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
